// 跨组件通信
import { Button } from "antd";
import React, { useState } from "react";

// npm install emitter
import { EventEmitter } from "emitter";
let emitter = new EventEmitter();

function Parent() {
  return (
    <div>
      <Son />
      <Child />
    </div>
  );
}

function Son() {
  const [number, setNumber] = useState(0);
  const handleClick = () => {
    setNumber(number + 1);
  };
  React.useEffect(() => {
    // 绑定事件
    emitter.once("childFn", (value: number) => {
      setNumber(number + value);
    });

    // return () => {
    //   emitter.off("childSay"); /* 解绑事件 */
    // };
  }, [number]);

  return (
    <div>
      <Button type="primary" onClick={handleClick}>
        Son +
      </Button>
      <p>{number}</p>
    </div>
  );
}

function Child() {
  const handleClick = () => {
    // 要修改 Son 中的数据 触发事件
    emitter.emit("childFn", 10);
  };
  return (
    <div>
      <Button type="primary" onClick={handleClick}>
        chang
      </Button>
    </div>
  );
}

export default Parent;
